//
//  ZCountDownButton.m
//  WeClubs
//
//  Created by Zed Link on 29/3/2017.
//  Copyright © 2017 Zed. All rights reserved.
//

#import "ZCountDownButton.h"

@interface ZCountDownButton () {
    NSString *_verifyTitle;
    UIColor *_verifyColor;
    NSString *_countDownTitle;
    UIColor *_countDownColor;
}

/** 是否正在进行倒计时 */
@property (assign, nonatomic) BOOL isCountDowning;

@end

@implementation ZCountDownButton

static NSUInteger _CountingValue = 0;
static dispatch_source_t _timer;

+ (instancetype)countDownButton
{
    ZCountDownButton *btn = [self buttonWithType:UIButtonTypeCustom];
    
    return btn;
}

- (void)willMoveToWindow:(UIWindow *)newWindow
{
    if (newWindow != nil) {
        // 即将显示到屏幕上
        [self endCountDown];
        [self beginCountDownWithTime:0];
    }
}

- (void)setVerifyStateTitle:(NSString *)title andColor:(UIColor *)color;
{
    [self setTitle:title forState:UIControlStateNormal];
    _verifyTitle = title;
    [self setTitleColor:color forState:UIControlStateNormal];
    _verifyColor = color;
}

- (void)setCountDownStateTitle:(NSString *)title andColor:(UIColor *)color
{
    _countDownTitle = title;
    _countDownColor = color;
}

- (void)beginCountDownWithTime:(NSTimeInterval)time
{
//    UIApplicationDidBecomeActiveNotification
    
//    ZLog(@"Counting Value: %ld", _CountingValue);
    
    if (_CountingValue == 0) {
        _CountingValue = time;
    }
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    // 新建定时器 (dispatch_walltime, 在后台时定时器也会执行)
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (_CountingValue <= 0) {
            // ========== 倒计时结束 ==========
            _isCountDowning = NO;
            dispatch_source_cancel(_timer);
            
            // 主线程更新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setTitle:_verifyTitle forState:UIControlStateNormal];
                self.titleLabel.text = _verifyTitle;
                [self setTitleColor:_verifyColor forState:UIControlStateNormal];
                
                self.userInteractionEnabled = YES;
            });
            
        } else {
            // ========== 开始倒计时 ==========
            _isCountDowning = YES;
            
            NSString *title = [NSString stringWithFormat:@"%@ %.1ld", _countDownTitle, (unsigned long)_CountingValue];
//            ZLog(@"%@", title);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setTitle:title forState:UIControlStateNormal];
                [self setTitleColor:_countDownColor forState:UIControlStateNormal];
                
                self.userInteractionEnabled = NO;
            });
            _CountingValue--;
        }
    });
    dispatch_resume(_timer);
}

- (void)endCountDown
{
    if (_isCountDowning == YES) {
        dispatch_source_cancel(_timer);
    }
}

- (void)dealloc
{
    ZLog(@"%@ is dealloc", NSStringFromClass([self class]));
}

@end
